import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'

const API_BASE_URL = 'http://localhost:5000/api'

export default function CreateCircleDialog({ open, onOpenChange, onSuccess, user }) {
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const handleSubmit = async (e) => {
    e.preventDefault()
    
    if (!name.trim()) {
      setError('请输入圈子名称')
      return
    }

    setLoading(true)
    setError('')

    try {
      const response = await fetch(`${API_BASE_URL}/circles/circles`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: name.trim(),
          description: description.trim(),
          creator_id: user.id,
        }),
      })

      const data = await response.json()

      if (response.ok) {
        // 重置表单
        setName('')
        setDescription('')
        setError('')
        onSuccess()
      } else {
        setError(data.error || '创建圈子失败')
      }
    } catch (err) {
      setError('网络错误，请重试')
    } finally {
      setLoading(false)
    }
  }

  const handleClose = () => {
    setName('')
    setDescription('')
    setError('')
    onOpenChange(false)
  }

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>创建新圈子</DialogTitle>
          <DialogDescription>
            创建一个新的旅游圈子，邀请朋友一起分享位置和聊天
          </DialogDescription>
        </DialogHeader>
        
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="circle-name">圈子名称 *</Label>
            <Input
              id="circle-name"
              placeholder="例如：丽江徒步圈"
              value={name}
              onChange={(e) => setName(e.target.value)}
              maxLength={50}
            />
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="circle-description">圈子描述（可选）</Label>
            <Textarea
              id="circle-description"
              placeholder="简单描述一下这次旅行..."
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              maxLength={200}
              rows={3}
            />
          </div>
          
          {error && (
            <div className="text-sm text-red-600">
              {error}
            </div>
          )}
          
          <div className="flex space-x-2 pt-4">
            <Button
              type="button"
              variant="outline"
              onClick={handleClose}
              className="flex-1"
            >
              取消
            </Button>
            <Button
              type="submit"
              disabled={loading}
              className="flex-1 bg-walker-orange hover:bg-walker-orange/90"
            >
              {loading ? '创建中...' : '创建圈子'}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  )
}

